package com.eimf.saf.security.action;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.eimf.saf.base.action.BaseAction;
import com.eimf.saf.base.querycomm.GenerateSearchUtil;
import com.eimf.saf.base.querycomm.SearchExpression;
import com.eimf.saf.base.strutsext.JsonResponseResult;
import com.eimf.saf.base.util.BaseCache;
import com.eimf.saf.base.util.PropsLoader;
import com.eimf.saf.security.entity.Staff;
import com.eimf.saf.security.exception.AppException;
import com.eimf.saf.security.exception.StaffPasswordErrorException;
import com.eimf.saf.security.exception.StaffStatusException;
import com.eimf.saf.security.service.OrganizeOperationLogService;
import com.eimf.saf.security.service.StaffService;
import com.eimf.saf.security.util.AppContant;
import com.eimf.saf.security.util.ImageCodeUtil;
import com.eimf.saf.security.util.secret.PasswordUtil;

/**
 * @author eden
 * @date 2013-11-13 下午2:01:57
 * @Description: 用户信息action
 */
@Controller
@Scope("prototype")
public class StaffAction extends BaseAction
{
    private static final long serialVersionUID = 1L;

    private static Log logger = LogFactory.getLog(StaffAction.class);

    public Staff _paraStaff = new Staff();

    @Autowired
    private StaffService staffServ;

    @Autowired
    private PropsLoader propsLoader;

    @Autowired
    private OrganizeOperationLogService operationLogSer;

    private String validcode;

    public String doLogin()
    {
        JsonResponseResult responseResult = JsonResponseResult.createSuccess();
        boolean loginFlag = false;
        Staff q_staff = null;
        String msg = "";
        try
        {
            if (ImageCodeUtil.verifyAddCode(validcode, ServletActionContext.getRequest()))
            {
                final SearchExpression searchExp = GenerateSearchUtil.buildSearchExp(_paraStaff);
                q_staff = staffServ.find(searchExp);
                if (null == q_staff)
                {
                    throw AppException.createErrorException(this.getText("error.login.notExist.staff"));
                }
                verifyStaffPassword(q_staff);
                this.setToSession(AppContant.LOGIN_STAFF_INFO, q_staff);
                loginFlag = true;
            } else
            {
                msg = this.getText("security.action.LoginAction.inputImageCode.error");
            }
        } catch (final StaffPasswordErrorException e)
        {
            if (true)// SysUtils.usingPasswordLockPolicy())
            {
                if (q_staff.getStatus() == 11)
                {
                    msg = this.getText("error.login.password.mismatch.locked",
                            BaseCache.getSystemParm("PWD_ERR_TIMES_LIMIT"),
                            BaseCache.getSystemParm("PWD_LOCK_TIME_DESC"));
                } else
                {
                    msg = this.getText("error.login.password.mismatch.tolock",
                            String.valueOf(operationLogSer.findPasswordErrorTimesByStaffId(q_staff.getStaffId())),
                            BaseCache.getSystemParm("PWD_ERR_TIMES_LIMIT"));
                }
            } else
            {
                msg = this.getText("error.login.password.mismatch");
            }
        } catch (final StaffStatusException e)
        {
            if (e.getStatus() == 11)
            {
                msg = this.getText("error.account.status.locked");
            } else if (e.getStatus() == 10)
            {
                msg = this.getText("error.account.status.overdue");
            } else if (e.getStatus() == 12)
            {
                msg = this.getText("error.account.status.locked");
            } else if (e.getStatus() == 21)
            {
                msg = this.getText("error.account.status.expired");
            } else
            {
                msg = this.getText("error.account.status.exception");
            }
            responseResult = JsonResponseResult.createFalied(msg);
            super.jsonResult = JSONObject.fromObject(responseResult).toString();
        } catch (final AppException app)
        {
            msg = this.getText(app.getMessage());
        } catch (final Exception e)
        {
            StaffAction.logger.error(e);
            msg = this.getText("SAF.action.Query.exception");
        }
        if (!loginFlag)
        {
            responseResult = JsonResponseResult.createFalied(msg);
        }
        super.jsonResult = JSONObject.fromObject(responseResult).toString();
        StaffAction.logger.debug(super.jsonResult);
        return BaseAction.JSON;
    }

    /**
     * 
     * 验证用户信息
     * 
     * @param loginname
     * @param password void
     * @exception
     * @since 1.0.0
     */
    private void verifyStaffPassword(final Staff qStaff) throws StaffStatusException, StaffPasswordErrorException
    {
        // 判断是否允许过期的号码可以自行修改密码
        if (null != propsLoader.props.getProperty("password.expired.can.unlock.self")
                && propsLoader.props.getProperty("password.expired.can.unlock.self").equals("true"))
        {
            if ((qStaff.getStatus() != -1) && (qStaff.getStatus() != 0) && (qStaff.getStatus() != 1)
                    && (qStaff.getStatus() != 10))
            {
                throw new StaffStatusException(qStaff.getStatus());
            } else if ((qStaff.getStatus() == 10)
                    && ((_paraStaff.getPassWord() == null) || (!PasswordUtil.verifyPassword(
                            String.valueOf(qStaff.getStaffId()), _paraStaff.getPassWord(), qStaff.getPassWord()))))
            {
                throw new StaffStatusException(qStaff.getStatus());
            }

        } else if ((qStaff.getStatus() != -1) && (qStaff.getStatus() != 0) && (qStaff.getStatus() != 1))
        {
            throw new StaffStatusException(qStaff.getStatus());
        }

        if (null == _paraStaff.getPassWord())
        {
            throw new StaffPasswordErrorException();
        }

        if (!PasswordUtil.verifyPassword(String.valueOf(qStaff.getStaffId()), _paraStaff.getPassWord(),
                qStaff.getPassWord()))
        {
            throw new StaffPasswordErrorException();
        }
    }

    /**
     * validcode
     * 
     * @return the validcode
     * @since 1.0.0
     */

    public String getValidcode()
    {
        return validcode;
    }

    /**
     * @param validcode the validcode to set
     */
    public void setValidcode(final String validcode)
    {
        this.validcode = validcode;
    }
}
